package com.example.eurekaserverclient.gclconverter;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.util.Arrays;

/**
 * @Author gcl
 * @Date 2020/7/2 9:39
 */
public class UnifyMessageConverter extends FastJsonHttpMessageConverter {

    public UnifyMessageConverter() {
        super();
        setSupportedMediaTypes(Arrays.asList(
                MediaType.APPLICATION_JSON,
                MediaType.TEXT_PLAIN,
                MediaType.TEXT_HTML
        ));
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if (!(object instanceof UnifyResponse)) {
            object = new UnifyResponse(object);
        }

        // 当返回的是string时，默认content-type是text/plain，所以这里再设置一次
        outputMessage.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        super.writeInternal(object, outputMessage);
    }
}
